//
//  SystemMessageCenter.m
//  安好
//
//  Created by qinlongqing on 14/12/12.
//  Copyright (c) 2014年 lianchuangbrother. All rights reserved.
//

#import "SystemMessageCenter.h"
#import "AppConfig.h"
#import "CLDataBaseController.h"
#import "ConsultList.h"
#import "PeerList.h"

static SystemMessageCenter *instance = nil;

@interface SystemMessageCenter ()
{
    BOOL isLoading;
}
@end

@implementation SystemMessageCenter

+ (SystemMessageCenter *)instance{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });
    return instance;
}

- (void)loadDataForIsFirstResign:(BOOL)isFirstResign{
    if ([[UserManager shareInstance] getUserIsLogin].length > 0) {
        if (isLoading) {//已经有正在加载的请求
            
        }
        else{
            isLoading = YES;
            NSDictionary *parameters;
            if (isFirstResign == YES) {
                parameters = @{@"platform": kPlatform,@"version":kVersion,@"isfirstregister":@"1"};
            }
            else{
                parameters = @{@"platform": kPlatform,@"version":kVersion,@"isfirstregister":@"0"};
            }
            [[AFHTTPRequestOperationManager manager] POST:[NSString stringWithFormat:@"%@%@",kBaseURL,kAnHaoSecretaryURL] parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
                isLoading = NO;
                
                NSNumber * statusNum = [responseObject objectForKey:@"status"];
                NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
                NSString * statusString = [numberFormatter stringFromNumber:statusNum];
                if ([statusString isEqualToString:@"1"]) {
                    NSDictionary *allMessages = [responseObject valueForKey:@"data"];
                    NSInteger currentLoginUserID = [[[UserManager shareInstance] getUserInfo].uid integerValue];
                    NSInteger returnedUserID = [[[allMessages valueForKey:@"user"] valueForKey:@"uid"] integerValue];
                    if (returnedUserID == currentLoginUserID) {
                        //                [[NSNotificationCenter defaultCenter] postNotificationName:kDidGetAndStoreMessageNotification object:nil userInfo:[NSDictionary dictionaryWithObjectsAndKeys:[allMessages valueForKey:@"message"],kDidGetMessageUserInfoKey, nil]];
                        
                        //安好订阅
                        NSArray *newestArray = [allMessages valueForKey:@"news"];
                        if (newestArray.count > 0) {
                            [self insertSecretaryNewsMessageWithArray:newestArray];
                            
                            [[NSNotificationCenter defaultCenter] postNotificationName:kDidGetAndStoreNewsNotification object:nil];
                        }
                        //1:同行   2:咨询  3:赞   4:圈子回复
                        NSArray *allNoticeMessage = [allMessages valueForKey:@"notice"];
                        if (allNoticeMessage.count > 0) {
                            [self insertSecretaryNoticeMessageWithArray:[allMessages valueForKey:@"notice"]];//收到notice消息后，存入数据库
                            [[NSNotificationCenter defaultCenter] postNotificationName:kDidGetAndStoreNoticeNotification object:nil];
                        }
                        //安好秘书
                        NSArray *allSystemMessage = [allMessages valueForKey:@"system"];
                        if (allSystemMessage.count > 0) {
                            for (NSInteger i=0; i<allSystemMessage.count; i++) {
                                [[CLDataBaseController instance] insertSecretarySystemMessageWithModel:[[SecretaryModel alloc]initWithDict:[allSystemMessage objectAtIndex:i]]];
                            }
                            [[NSNotificationCenter defaultCenter] postNotificationName:kDidGetAndStoreSystemNotification object:nil];
                        }
                    }
                }
                else if ([statusString isEqualToString:@"-10"]){
                    [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"SelfUidKey"];
                }else{
                    
                }
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                isLoading = NO;
                
                MyNSLog("请求失败！error=%@",error);
            }];
        }
    }
}

//安好订阅相关
- (void)insertSecretaryNewsMessageWithArray:(NSArray *)newestArray{
    [[CLDataBaseController instance] insertTheNewestSubscibeNewsMessageWithArray:newestArray];
}

- (BOOL)isHaveNoReadSubscibeNews{
    return [[CLDataBaseController instance] isHaveNoReadedSubscibeNewsMessage];
}

- (void)updataSecretaryNewsMessageToReaded{
    [[CLDataBaseController instance] updataSecretaryNewsMessageToReaded];
}

- (SubscibeModel *)getTheNewestSecretaryNewsMessage{
    return [[CLDataBaseController instance] getTheNewestSecretaryNewsMessage];
}


//安好秘书相关
- (BOOL)isHaveNoReadedSystemMessage{
    return [[CLDataBaseController instance] isHaveNoReadedSystemMessage];
}

- (NSArray *)getAllSystemMessage{
    return [[CLDataBaseController instance] selectAllSecretarySystemMessage];
}

- (void)updataSecretarySystemMessageToReaded{
    [[CLDataBaseController instance] updataSecretarySystemMessageToReaded];
}

- (SecretaryModel *)getTheNewestSecretarySystemMessage{
    return [[CLDataBaseController instance] getTheNewestSecretarySystemMessage];
}

/**
 *  查看咨询、安好秘书和安好订阅有没有未读消息
 *
 *  @return 如果有返回YES
 */
- (BOOL)isHaveNoReadedMessageForAll{
    if ([self isHaveNoReadedSystemMessage]) {
        return YES;
    }
    if ([self isHaveNoReadSubscibeNews]) {
        return YES;
    }
    
    if ([ConsultList readUnreadCount] || [PeerList readUnreadCount]) {
        return YES;
    }
    return NO;
}


#pragma notice（安好圈子）相关
- (void)insertSecretaryNoticeMessageWithArray:(NSArray *)noticeMessageArray{
    [[CLDataBaseController instance] insertSecretaryNoticeMessageWithArray:noticeMessageArray];
}
- (NSArray *)selectSecretaryNoticeMessage{
    return [[CLDataBaseController instance] selectSecretaryNoticeMessage];
}
- (NSArray *)selectAllNoReadedSecretaryNoticeMessage{
    return [[CLDataBaseController instance] selectAllNoReadedSecretaryNoticeMessage];
}
- (void)updataSecretaryNoticeMessageToReaded{
    [[CLDataBaseController instance] updataSecretaryNoticeMessageToReaded];
}

- (NoticeData *)getTheNewestSecretaryNoticeMessage{
    return [[CLDataBaseController instance] getTheNewestSecretaryNoticeMessage];
}



@end
